﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZerAx.Net;
using ZerAx.ObjectNotation;

namespace BlockOS.Server
{
    internal class PlayerManager
    {
        private GameServer server;

        public Dictionary<string, PlayerData> players = new();

        public PlayerManager(GameServer server)
        {
            this.server = server;

            server.ConnectManager.OnDisconnect += OnReceiveDisconnect;
        }

        public void OnReceiveDisconnect(int connId)
        {
            foreach (var (name, player) in players)
            {
                if (player.connId == connId)
                {
                    RemovePlayer(name);
                    break;
                }
            }
        }

        public void OnReceiveLogin(int connId, Packet packet)
        {
            var name = packet.ReadData(r => r.ReadString());
            int entityId;
            if (players.TryGetValue(name, out var playerData))
            {
                entityId = playerData.entityId;
                playerData.connId = connId;
            }
            else
            {
                entityId = server.GetModule<EntityManager>().AddEntity(new EntityData
                {
                    name = name,
                    typeId = (int)EntityTypeId.Player,
                    x = 0,
                    y = 10,
                    z = 0,
                });
                AddPlayer(name, new PlayerData { entityId = entityId, connId = connId });
            }
            
            server.SendProtocol(connId, ProtocolId.RESPONSE_LOGIN, Zon.Compound(("name", name), ("entityId", entityId)).Serialize);

            server.LogMessage($"Login message received from {connId}.");
            server.LogMessage($"Player {name} created, eid: {entityId}");
        }

        public void AddPlayer(string playerName, PlayerData player)
        {
            players.Add(playerName, player);
        }

        public void RemovePlayer(string playerName)
        {
            players.Remove(playerName);
        }
    }
}
